import {
  type_checkbox,
  type_name_key_cpc,
  type_name_key_product_type,
  type_name_key_supplier_id,
  type_src_demand,
  type_src_exhibitor,
  type_src_exhibits,
  type_src_purchaser,
  type_src_supplier
} from '@/tim/constact'
import Cookie from 'js-cookie'
import ajax from '@/tim/ajax'
import moment from 'moment';
/*
 *在BodyMap提交验证之前 验证
 * 具体需要验证
 * 1，mandatory=1不填
 * 2.手机号
 * 3 邮箱*/

export function windowMobileSetRem () {
  // 基准大小
  const baseSize = 32

  // 设置 rem 函数
  function setRem () {
    // 当前页面宽度相对于 1080 宽的缩放比例，可根据自己需要修改。
    const scale = document.documentElement.clientWidth / 1080
    // 设置页面根节点字体大小
    document.documentElement.style.fontSize =
      baseSize * Math.min(scale, 2) + 'px'
  }

  // 初始化
  setRem()
  // 改变窗口大小时重新设置 rem
  window.onresize = function () {
    setRem()
  }
}

export function jsonParseSafe (str) {
  try {
    return JSON.parse(str)
  } catch (e) {
    return str
  }
}

export function isNil (str) {
  if (str === null) {
    console.log(11)
    return true
  }
  if (typeof str === 'undefined') {
    console.log(22)
    return true
  }
  if (str === '') {
    console.log(33)
    return true
  }
  return false
}

/*
 * 入参str
 * 出去之后一定变成 array
 * 比如'1,2,3'   '[1,2,3]'
 * */
export function becomeArray (str) {
  if (!str) {
    return []
  }
  if (!str.indexOf) {
    return []
  }
  str = jsonParseSafe(str)
  if (str.constructor == Array) {
    return str.filter(item => !isNil(item))
  }
  if (str.constructor == Number) {
    return str
  }
  if (str.constructor === String) {
    if (str.indexOf(',') >= 0) {
      return str.split(',').filter(item => !isNil(item))
    }
    if (str.indexOf('\n') >= 0) {
      return str.split('\n').filter(item => !isNil(item))
    }
    return [str]
  }

  // 如果不是好的格式 直接【】
  return []
}

// 提交的时候 把array变成str
export function valueDuoxuanForPostStr (array) {
  if (!array) return ''
  if (array && array.constructor === String && array[array.length - 1] == ',') {
    array.substr[array.length - 1]
  }
  if (array && array.constructor === String) {
    return array
      .split(',')
      .filter(item => !isNil(item))
      .join(',')
  }
  if (array && array.constructor === Array) {
    return array.join(',')
  }
  return ''
}

// tags 类型 key:value   value 这个value如果是array都 '1,2,3'
export function valueDuoxuanForPostStr4Tags (array) {
  if (!array) return ''
  if (array && array.constructor === String && array[array.length - 1] == ',') {
    array.substr[array.length - 1]
  }
  if (array && array.constructor === String) {
    return array
      .split(',')
      .filter(item => !isNil(item))
      .join(',')
  }
  if (array && array.constructor === Array) {
    return array.join(',')
  }
  return ''
}

// 其他的类型  类型 key:value   value 这个value如果是array都 JSON.stringfy([1,2,3])
export function valueDuoxuanForPostStr4jsonArray (array) {
  if (!array) return []
  if (array && array.constructor === String && array[array.length - 1] == ',') {
    array.substr[array.length - 1]
  }
  if (array && array.constructor === String) {
    return JSON.stringify(array.split(',').filter(item => !isNil(item)))
  }
  if (array && array.constructor === Array) {
    return JSON.stringify(array)
  }
  return []
}

export function isDisplay (strDisplay) {
  if (strDisplay.indexOf('zh') >= 0) {
    return true
  }
  if (strDisplay.indexOf('en') >= 0) {
    return true
  }
  return false
}

export function validateBodyMapBeforePost (bodyMap) {
  var errorMessage = ''
  for (let i = 0; i < bodyMap.length; i++) {
    console.log(bodyMap, isNil(bodyMap[i].value), isDisplay(bodyMap[i].display), 'bodyMap123')
    if (
      bodyMap[i].mandatory == mandatory_require &&
      isNil(bodyMap[i].value) &&
      isDisplay(bodyMap[i].display)
    ) {
      errorMessage = `${window._vm.lang == 'zh' ? bodyMap[i]['nameZh'] + '不能为空' : bodyMap[i]['nameEn'] + ' Cannot be Empty'
      }`
      return errorMessage
    }
    if (bodyMap[i].nameKey == type_name_key_product_type && bodyMap[i].mandatory == mandatory_require && bodyMap[i].value.length == 0) {
      errorMessage = `${window._vm.lang == 'zh' ? bodyMap[i]['nameZh'] + '不能为空' : 'Interested Products Cannot be Empty'}`
      return errorMessage
    }
  }
  for (let i = 0; i < bodyMap.length; i++) {
    if (bodyMap[i].nameKey == 'email' && bodyMap[i].value && !isEmail(bodyMap[i].value)) {
      console.log(bodyMap[i].nameKey, bodyMap[i].value, !reg_email.test(bodyMap[i].value), 'email')
      errorMessage = 'Not in Email format'
      return errorMessage
    }
  }
  if (errorMessage) return errorMessage
  // return errorMessage;
}

export function validateMobile (str) {
  if (!str) {
    return '手机不能为空'
  }
  if (!reg_mobile.test(str)) {
    return '不是手机格式'
  }
  return true
}

export function uuid () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0;
    var v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
export function params2url (params) {
  var url = ''
  // require('lodash.map')(params, (value, key) => {
  //   url += `${key}=${value}&`
  // })
  if (url) {
    url = url.substr(0, url.length - 1)
  }
  return url
}

function setStrArray2Array (str) {
  if (!str) {
    return []
  }
  var indexOf = str.indexOf(',')
  if (indexOf >= 0) {
    return str && str.split && str.split(',')
  }
  indexOf = str.indexOf('\n')
  if (indexOf >= 0) {
    return str && str.split && str.split('\n')
  }

  return str
}

/*
 * 把变量bodys 和 defaults 整合在一起
 * */
export function mergeBodyAndDefauts (body, defaults) {
  var _body = body || []
  var _defaults = defaults || []
  if (!_body || _body.length == 0) {
    return _defaults
  }
  for (let i = 0; i < _body.length; i++) {
    var bodyItem = _body[i]
    for (let j = 0; j < _defaults.length; j++) {
      var defaultItem = _defaults[j]
      if (bodyItem.nameKey === defaultItem.nameKey) {
        if (isNil(bodyItem.defaults)) {
          _body[i].defaults = defaultItem.defaults
        }
        // display 主要看 bodyItem
        _body[i].display = bodyItem.display
        // display 主要看 defaultItem
        _body[i].parameter = becomeArray(defaultItem.parameter)
        // console.log("bodyItem.parameter=======>",defaultItem.nameKey,bodyItem.parameter)
        // console.log("defaultItem.parameter=======>",defaultItem.nameKey,defaultItem.parameter)
      }
    }
  }
  return _body
}

export function getSupplierIdInBodyMap (bodyMap) {
  var index = bodyMap.findIndex(
    item => item.nameKey === type_name_key_supplier_id
  )
  if (index >= 0) {
    return bodyMap[index]
  }
  return null
}

export function accessToken () {
  return '123456'
}

export function timeStamp () {
  return new Date().getTime() + ''
}

export function isEmail (value) {
  return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g.test(value)
}

export function isMobile (value) {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    return false
  } else {
    return true
  }
}

/*
 * 生成vue的props
 * type可以是object
 * eg1:createProp({a:1,b:2})
 * eg2:createProp(String,{default:'lmt'})
 * */
export function createProp (type, options = { required: false, default: '' }) {
  if (type.constructor === Object && type !== Object) {
    return {
      type: Object,
      required: options.required,
      default: type
    }
  }
  return {
    type: type,
    required: options.required,
    default: options.default
  }
}

export function getUserIdInSession () {
  var str = sessionStorage.getItem('userId')
  if (!str) {
    return ''
  }
  return str
}

// 界面上的 bodyMap对象变成一个可以提价的body对象
export function bodyAndValue2postObject (bodyAndValue) {
  var data = {}
  bodyAndValue.map(item => {
    if (
      item.nameKey &&
      item.type == type_checkbox &&
      item.nameKey != type_name_key_product_type
    ) {
      data[item.nameKey] = valueDuoxuanForPostStr(item.value)
      return false
    }
    if (item.nameKey && item.nameKey == type_name_key_product_type) {
      data[item.nameKey] = valueDuoxuanForPostStr4Tags(item.value)
      // valueDuoxuanForPostStr(setRightData(item.value))
      return false
    }
    // 国家  省市县
    if (item.nameKey == type_name_key_cpc) {
      if (!item.value) {
        data['country'] = ''
        data['province'] = ''
        data['city'] = ''
        return false
      }
      if (item.value.constructor === String) {
        data['country'] = ''
        data['province'] = ''
        data['city'] = ''
        return false
      }
      var cpc = item.value
      data['country'] = cpc['country']
      data['province'] = cpc['province']
      data['city'] = cpc['city']
      return false
    }
    if (item.nameKey) {
      data[item.nameKey] = item.value
      return false
    }
  })
  return data
}

export function findMobileInBodyAndValue (bodyAndValue) {
  var index = bodyAndValue.findIndex(item => item.nameKey === 'mobilePhone')
  return bodyAndValue[index]
}

/*

* body  字段类型数组
* datamap 字段的值
合并 body  datamap
让body[index].value=datamap[nameKey]
* */
export function createBodyMapBymergeBodyAndDataMap (bodys, datamap) {
  var supplierMapAndbodys = bodys.map(item => {
    item.value = datamap[item.nameKey]
    item.timeStamp = timeStamp()
    /* 处理如果是cpc的 合并成对象*/
    if (item.nameKey === type_name_key_cpc) {
      item.value = {
        country: datamap['country'],
        province: datamap['province'],
        city: datamap['city']
      }
    }
    // 处理tags='[1,2,3]'
    if (item.nameKey === type_name_key_product_type) {
      if (!item.value) {
        item.value = []
      }
      item.mandatory = '1'
      if (item.value.constructor === String && item.value[0] == '[') {
        var _value = item.value.slice(1, item.value.length - 1)
        item.value = _value
          .split(',')
          .map(item => item.trim())
          .filter(item => !isNil(item))
      }
    }
    return item
  })
  return supplierMapAndbodys
}

export function getCookie (key) {
  var result = sessionStorage.getItem(key) || Cookie.get(key) || ''
  return result
}

export function setCookie (
  key,
  value,
  option = {
    time: 2
  }
) {
  sessionStorage.setItem(key, value)
  Cookie.set(key, value, { expires: option.time / 24 })
}

export function setSession (
  key,
  value,
  option = {
    time: 2
  }
) {
  sessionStorage.setItem(key, value)
}

export function getSession (
  key,
) {
  return sessionStorage.getItem(key)
}

export function getLoginUser () {
  var user = jsonParseSafe(getCookie('user'))
  if (!user) {
    user =
      window._vm &&
      window._vm.$store.state.message &&
      window._vm.$store.state.message.currentUser
    return user
  }
  return user
}

export function setLoginUser (key, value) {
  var user = jsonParseSafe(getCookie('user'))
  user[key] = value
  setCookie('user', JSON.stringify(user))
  return user
}

export function deepClone (obj) {
  const newObj = Array.isArray(obj) ? [] : {}
  if (obj && typeof obj === 'object') {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        newObj[key] =
          obj && typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]
      }
    }
  }
  return newObj
}

export function checkTypeVideo (file) {
  console.log('checkTypeVideo file fiulename', file, file.name)
  var tv_id = file.name
  var index = tv_id.indexOf('.') // （考虑严谨用lastIndexOf(".")得到）得到"."在第几位
  tv_id = tv_id.substring(index) // 截断"."之前的，得到后缀
  if (
    tv_id != '.mp4' &&
    tv_id != '.MP4' &&
    tv_id != '.rmvb' &&
    tv_id != '.avi' &&
    tv_id != '.ts'
  ) {
    // 根据后缀，判断是否符合视频格式
    return false
  } else {
    return true
  }
}

export function getQuery (str) {
  if (!str) return ''
  return window._vm && window._vm.$route && window._vm.$route.query[str]
}

export function getProjectId () {
  var projectId = getQuery('projectId')
  if (!projectId) {
    projectId =
      window._vm.$store.state.message &&
      window._vm.$store.state.message.currentUser.projectId
  }
  if (!projectId) {
    projectId = getCookie('projectId')
  }
  if (projectId == 'undefined') {
    return ''
  }
  window._vm.g.projectId = projectId
  console.log(projectId, 'projectId')
  return projectId
}

export function setProjectId (projectId) {
  var projectId = getProjectId()
  setCookie('projectId', projectId)
  return projectId
}

export function isDesMobile () {
  var isMobile = false
  var sUserAgent = navigator.userAgent.toLowerCase()
  var bIsIpad = sUserAgent.match(/ipad/i) == 'ipad'
  var bIsIphoneOs = sUserAgent.match(/iphone os/i) == 'iphone os'
  var bIsMidp = sUserAgent.match(/midp/i) == 'midp'
  var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == 'rv:1.2.3.4'
  var bIsUc = sUserAgent.match(/ucweb/i) == 'ucweb'
  var bIsAndroid = sUserAgent.match(/android/i) == 'android'
  var bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce'
  var bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile'
  var isShare = location.href.indexOf('/share/') // 是否为分享页面
  var isBaiduSpider = sUserAgent.match(/baiduspider/i) == 'baiduspider'
  var isGooleSpider = sUserAgent.match(/googlebot/i) == 'googlebot'
  var isAhrefsSpider = sUserAgent.match(/ahrefsBot/i) == 'ahrefsBot'
  var is360Spider = sUserAgent.match(/360spider/i) == '360spider'
  var isSOSOSpider = sUserAgent.match(/sosospider/i) == 'sosospider'
  var isSogouSpider = sUserAgent.match(/sogou spider/i) == 'sogou spider'
  var isAlibabaSpider = sUserAgent.match(/alibaba/i) == 'alibaba'
  var isXiaomi = sUserAgent.match(/mi\s/i) == 'mi'
  var isXiaomi2s = sUserAgent.match(/mix\s/i) == 'mix'
  var isRedmi = sUserAgent.match(/redmi/i) == 'redmi'
  var isredmix = sUserAgent.match(/redmi/i) == 'redmix'

  if (
    bIsIpad ||
    bIsIphoneOs ||
    bIsMidp ||
    bIsUc7 ||
    bIsUc ||
    bIsAndroid ||
    bIsCE ||
    bIsWM
  ) {
    // 移动设备
    if (
      isShare < 0 &&
      !isBaiduSpider &&
      !isGooleSpider &&
      !isAhrefsSpider &&
      !is360Spider &&
      !isSOSOSpider &&
      !isSogouSpider &&
      !isAlibabaSpider &&
      !isXiaomi &&
      !isXiaomi2s &&
      !isRedmi &&
      !isredmix
    ) {
      // $('#mobile').attr('href', '/static/css/mobile.css')
      isMobile = true
    } else {
      isMobile = false
    }
  } else {
    isMobile = false
  }
  return isMobile
}

/**
 * @desc  标签 根据语言自动切换
 *  */

export function gobackYiWu () {
  var user = getLoginUser()
  var projectId = getProjectId()
  // 如果登陆了
  if (!user.id) {
    if (!projectId) {
      location.href = `/font/toLogin`
      return false
    }
    if (projectId) {
      location.href = `/font/toLogin?projectId=${projectId}`
      return false
    }
    return false
  } else {
    if (user == type_src_supplier) {
      routerUtil.push(`/user/yiwu/exhibition/index`)
      return false
    } else {
      routerUtil.push(`/user/yiwu/purchaser/index`)
      return false
    }
  }
}

export function getNickName (user) {
  return getUserName()
}

export function safeTags (tags) {
  if (!tags) return ''
  if (tags.constructor === String && tags[0] == '[') {
    tags = tags && tags.slice && tags.slice(1, tags.length - 1)
    tags = tags && tags.split && tags.split(',')
    tags = tags.map(_item => _item.trim()).filter(item => !isNil(item))
  }
  return tags
}

export default function downTimeHHMMSS (endTime) {
  // this.timeList = []; // 循环之前清空上一秒存入的数据，让数组始终保持最新一条的数据
  // for (var i = 0; i < this.endTime.length; i++) {
  // console.log(moment().format('X'));//获取当前时间的时间戳
  // console.log(moment(this.endTime[i].time).format('X'));//获取指定时间的时间戳
  // console.log(moment(this.endTime[i].time).format('X') - moment().format('X'));//获取时间戳的差值
  const timeVal = moment(endTime).format('X') - moment().format('X')
  // 时间戳转换
  var d = Math.floor(timeVal / (24 * 3600))
  var h = Math.floor((timeVal - 24 * 3600 * d) / 3600)
  var m = Math.floor((timeVal - 24 * 3600 * d - h * 3600) / 60)
  var s = Math.floor(timeVal - 24 * 3600 * d - h * 3600 - m * 60)
  // console.log(d + '天' + hh + '时' + mm + '分' + ss + '秒'); // 打印出转换后的时间
  //  当时分秒小于10的时候补0
  var hh = h < 10 ? '0' + h : h
  var mm = m < 10 ? '0' + m : m
  var ss = s < 10 ? '0' + s : s
  // this.timeList.push(d + '天' + hh + '时' + mm + '分' + ss + '秒'); // 将三个倒计时日期添加到一个空的数组中
  // }
  // console.log(this.timeList); // 打印结果
  return `${hh}时${mm}分${ss}秒`
}

// 下划线转换驼峰
export function toHump (name) {
  return name.replace(/\_(\w)/g, function (all, letter) {
    return letter.toUpperCase()
  })
}

// 驼峰转换下划线
export function toLine (name) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase()
}

export function createA (href, target) {
  var a = document.createElement('a')
  a.setAttribute('href', href)
  a.setAttribute('target', target || '_blank')
  a.setAttribute('id', 'startTelMedicine')
  // 防止反复添加
  if (document.getElementById('startTelMedicine')) {
    document.body.removeChild(document.getElementById('startTelMedicine'))
  }
  document.body.appendChild(a)
  a.click()
}

export function throttle (fn, delay) {
  let last = 0
  return function () {
    const cur = +new Date() // +是一元操作符，利用js隐式转换将其他类型变为数字类型
    if (cur >= last + delay) {
      fn.apply(this, arguments)
      last = cur
    }
  }
}

export function uuidNumber () {
  var len = len || 9
  var chars = '0123456789'
  var maxPos = chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

async function ajaxUserSig (UserId) {
  var userSig = await ajax.post('/trtcorim/getUsgSign', {
    UserId: UserId
  })
  // var generator = new window.LibGenerateTestUserSig(SDKAPPID, SECRETKEY, EXPIRETIME);
  // var userSig = generator.genTestUserSig(UserId);
  return userSig.data.result
}

export function getUserTags () {
  var tags111 = getLoginUser().tags
  var tags = jsonParseSafe(tags111)
  if (!tags) {
    tags = []
  }
  var tags_ = []
  if (tags[0] == '[') {
    var str_ = tags.slice(1, tags.length - 1)
    tags_ = str_.split(',')
  } else {
    tags_ = [tags111]
  }
  return tags_
}

/**
 * @desc 获取名称 根据用户类型
 * */
export function getUserName () {
  var user = jsonParseSafe(getCookie('user'))
  // var lang = sessionStorage.getItem('lang') || 'en'
  if (!user) return ''
  return user.name
  // if (user == type_src_supplier) {
  //   var name = user.contactName || user.company || user.contact
  //   var nameEn = user.contactName || user.companyEn || user.contactEn
  //   return (lang == 'zh' ? name : nameEn) || user.company || user.contact || user.userName
  // } else {
  //   var name = user.contact || user.company
  //   var nameEn = user.contactEn || user.companyEn
  //   return (lang == 'zh' ? name : nameEn) || user.company || user.contact || user.userName
  // }
}

// 判断是不是登陆
export function isLogin () {
  // var user = getLoginUser();
  var user = jsonParseSafe(sessionStorage.getItem('user'))
  return user && user.id
}

var index = 0

function compare (property) {
  return function (a, b) {
    var value1 = a[property]
    var value2 = b[property]
    return value1 - value2
  }
}

export function setSort4Array (array = []) {
  return array.map(item => {
    if (!item._sort) {
      item._sort = index
      index++
    }
    return item
  })
}

export function mergeArray (a1, a2, keys, or) {
  if (!a2) {
    return a1
  }
  var _key = 'id'
  _key = keys || 'id'
  var a1 = setSort4Array(a1)
  var finshArray = a1
  a2.map(item2 => {
    var isExit = false
    a1.map(item1 => {
      if (item1[_key] == item2[_key]) {
        isExit = true
      }
    })
    if (!isExit) {
      finshArray.push(item2)
    }
  })

  var newList = finshArray.sort(compare('_sort'))
  return newList
}

export function activityDetail () {
  var activity = jsonParseSafe(getCookie('activity'))
  if (activity && activity.id) {
    return Promise.resolve(activity)
  } else {
    const params = {
      projectId: sessionStorage.getItem('projectId') || getProjectId()
    }
    return queryActivity(params).then(res => {
      console.log('res && res.result  activityDetail', res, res && res.data)
      setCookie('activity', JSON.stringify(res && res.data))
      return Promise.resolve(res && res.data)
    })
  }
}

export function fixedCss () {
  setTimeout(() => {
    // console.log("=====  $('.select_btn')==>",  $('.select_btn'))
    $('.select_btn').css({
      background: getWindowThemeColorByMode(),
      borderColor: getWindowThemeColorByMode()
    })
  }, 500)
}

export function getUrlParamNative (n) {
  var e, r
  return (
    (r = new RegExp('(^|&)' + n + '=([^&]*)(&|$)')),
    (e = location.search.substr(1).match(r)),
    e !== null ? decodeURI(e[2]) : null
  )
}

/**
 * @desc
 * type_src_supplier
 *  */

export function getUserRoleType () {
  return getLoginUser()
}

// 获取本系统所有的tags  with name
export function getTagsWithName () {
  const matchCgsType = jsonParseSafe(sessionStorage.getItem('matchCgsType'))
  if (matchCgsType && matchCgsType.length != 0) {
    var matchCgsType_ = changeLang4matchCgsType(matchCgsType)
    return matchCgsType_
  } else {
    return getExhibitTypeList()
  }
}

export function changeLang4matchCgsType (matchCgsType) {
  var lang = this.lang
  var productTypeMap = jsonParseSafe(sessionStorage.getItem('productTypeMap'))
  for (let i = 0; i < matchCgsType.length; i++) {
    var one = productTypeMap[matchCgsType[i].type]
    var name = one[lang == 'zh' ? 'chinese' : 'english']
    matchCgsType[i].name = name
    if (matchCgsType[i] && matchCgsType[i].child) {
      for (let j = 0; j < matchCgsType[i].child.length; j++) {
        var one = productTypeMap[matchCgsType[i].child[j].type]
        var name = one[lang == 'zh' ? 'chinese' : 'english']
        matchCgsType[i].child[j].name = name
      }
    }
  }
  return matchCgsType
}

export function getExhibitTypeList () {
  return ajaxGetExhibitTypeList().then(res => {
    const { result, message, code } = res
    if (code === '0') {
      const purchaserLayout = jsonParseSafe(result && result.purchaserLayout)
      const matchCgsType =
        purchaserLayout &&
        purchaserLayout.filter(item => item.nameKey === 'tags')[0].cascades
      var productTypeMap = tree2array(matchCgsType)
      if (productTypeMap && productTypeMap.length) {
        sessionStorage.setItem('productTypeMap', JSON.stringify(productTypeMap))
      }
      var matchCgsType_ = formatCheckboxData(matchCgsType)
      sessionStorage.setItem('matchCgsType', JSON.stringify(matchCgsType_))
      return matchCgsType_
    } else {
      return []
    }
  })
}

export function formatCheckboxData (matchCgsType) {
  var lang = getUrlParamNative('lang') || sessionStorage.getItem('lang')
  var nameKey = lang == 'zh' ? 'chinese' : 'english'
  const newArr = [];
  let newItem = {
    name: '',
    type: '',
    allCheckType: [],
    checked: [],
    checkAll: false,
    child: []
  }
  for (let i = 0; i < matchCgsType.length; i++) {
    const item = matchCgsType[i]
    const { parent, subclass, chinese, id } = item
    if (parent) {
      newItem.name = parent[nameKey]
      newItem.type = parent.id
    } else {
      newItem.name = item[nameKey]
      newItem.type = id
    }
    if (subclass && subclass.length) {
      newItem.allCheckType = subclass.map(item => item.id)
      newItem.child = formatCheckboxData(subclass)
    }
    newArr.push(newItem)
    newItem = {
      name: '',
      type: '',
      allCheckType: [],
      checked: [],
      checkAll: false,
      child: []
    }
  }
  return newArr
}

export function tree2array (tree) {
  var array = jsonParseSafe(sessionStorage.getItem('productTypeMap')) || []
  for (let i = 0; i < tree.length; i++) {
    var treeItem = tree[i]
    array[treeItem && treeItem.parent && treeItem.parent.id] =
      treeItem && treeItem.parent
    for (let j = 0; j < (treeItem.subclass && treeItem.subclass.length); j++) {
      if (
        treeItem.subclass &&
        treeItem.subclass[j] &&
        treeItem.subclass[j].id
      ) {
        array[
          treeItem.subclass && treeItem.subclass[j] && treeItem.subclass[j].id
        ] = treeItem.subclass && treeItem.subclass[j]
      }
    }
  }
  return array
}

export function formatTags (selectTypes) {
  const matchCgsType = jsonParseSafe(sessionStorage.getItem('matchCgsType'))
  const tags = selectTypes.split(','); const newArr = []
  if (matchCgsType.length && selectTypes) {
    for (let i = 0; i < tags.length; i++) {
      const tag = tags[i]
      for (let j = 0; j < matchCgsType.length; j++) {
        const item = matchCgsType[j]
        if (item.type === tag) {
          for (let m = 0; m < item.child.length; m++) {
            const mItem = item.child[m]
            newArr.push(mItem.name)
          }
          break
        } else if (item.child.length) {
          for (let m = 0; m < item.child.length; m++) {
            const mItem = item.child[m]
            if (mItem.type === tag) {
              newArr.push(mItem.name)
            }
          }
        }
      }
    }
    return newArr
  }
  return newArr
}

export function getUserIdByUserRole (user) {
  if (user == type_src_supplier) {
    return user.id
  }
  return user.id
}

/*
* `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(255) DEFAULT NULL COMMENT '用户id',
  `type` int(1) DEFAULT NULL COMMENT '0:展商 1:观众 2:展品 3:需求',
  `operation` int(1) DEFAULT NULL COMMENT '0:点赞 1:收藏',
  `project_id` varchar(255) DEFAULT NULL COMMENT '活动id',
  `object_id` varchar(255) DEFAULT NULL COMMENT '对应类型id',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `src` int(10) DEFAULT NULL,
* */
export function ajaxLikeCollectOne (options) {
  return addCollect({
    'userId': getLoginUser().id,
    'type': options.type,
    'operation': options.operation,
    'objectId': options.objectId,
    'projectId': getProjectId(),
    'src': getLoginUser(),
  })
}

export function ajaxRemoveLikeCollectOne (id) {
  return delCollect({ id: id })
}

export function isLikeInList (objectId) {
  var old_zs_like_list = jsonParseSafe(getSession('collect_like_list')) || []
  var index = old_zs_like_list.findIndex(item => item.objectId == objectId)
  return index >= 0
}

export function findIndexLikeInList (objectId, operation) {
  var old_zs_like_list = jsonParseSafe(getSession('collect_like_list')) || []
  var index = old_zs_like_list.findIndex(item => {
    return item.objectId == objectId && operation == item.operation
  })
  return index
}

export function removeOneLikeInList (objectId, operation) {
  var index = findIndexLikeInList(objectId, operation)
  var old_zs_like_list = jsonParseSafe(getSession('collect_like_list')) || []
  old_zs_like_list.splice(index, 1)
  setSession('collect_like_list', JSON.stringify(old_zs_like_list))
  return old_zs_like_list
}

export function pushOneLikeInList (one) {
  var old_zs_like_list = jsonParseSafe(getSession('collect_like_list')) || []
  old_zs_like_list.push(one)
  setSession('collect_like_list', JSON.stringify(old_zs_like_list))
  return old_zs_like_list
}

export function getUserIdByInfoAndType (info) {
  var userId = info.id
  if (info.type == type_src_exhibitor) {
    userId = info.supplier_id || info.supplierId || info.id
  }
  if (info.type == type_src_purchaser) {
    userId = info.id
  }
  if (info.type == type_src_exhibits) {
    userId = info.supplierId
  }
  if (info.type == type_src_demand) {
    userId = info.purchaserId
  }

  // dto新增处理 objectType
  if (info.objectType == type_src_exhibitor) {
    userId = info.supplier_id || info.supplierId || info.id
  }
  if (info.objectType == type_src_purchaser) {
    userId = info.id
  }
  if (info.objectType == type_src_exhibits) {
    userId = info.supplierId
  }
  if (info.objectType == type_src_demand) {
    userId = info.purchaserId
  }
  return userId
}

export function uploadImageFile (file) {
  var _this = this
  var fileName = file.name
  if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(fileName)) {
    _this.$message({
      type: 'error',
      message: _this.$t('lang.mustPicture')
    })
    return false
  }
  const formData = new FormData()
  formData.append('file', file)
  this.loadingUploadButton = true
  return uploadThumbnail(formData).then(res => {
    this.loadingUploadButton = false
    if (res.code == 0) {
      this.modifyShow = true
      // this.createForm.imgUrl = res.data
      // console.log(this.queryParams)
      // this.$emit('imgUrl', res.data, this.queryParams)
      _this.$message({
        type: 'success',
        message: _this.$t('lang.uploadSuccess')
      })
      return res.data
    } else {
      _this.$message({
        type: 'error',
        message: _this.$t('lang.uploadFail')
      })
    }
  }).catch(e => {
    this.loadingUploadButton = false
    console.error('=uploadThumbnail=======>', e)
  })
}

/* 上传之前需的签名
* https://cloud.tencent.com/document/product/266/9239
* */
export function uploadGetSignature () {
  return axios.get(`/api/api3/backend/v2/livereturn/getSignature`).then(function (response) {
    return response.data.signature
  })
}

export function formatDate (value) {
  const date = new Date(value)
  const y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let m = date.getMinutes()
  m = m < 10 ? ('0' + m) : m
  let s = date.getSeconds()
  s = s < 10 ? ('0' + s) : s
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
}

export function liveStatusName (num) {
  // <!--      `status` int(1) DEFAULT NULL COMMENT '直播状态（ 0 初始，1 直播中,2 暂停,3 已停止）',-->
  const a = {
    0: window._vm.$t('lang.直播中'),
    1: window._vm.$t('lang.已结束'),
    // 1: window._vm.$t('lang.直播中'),
    2: window._vm.$t('lang.暂停'),
    // 3: window._vm.$t('lang.已暂停'),
  }
  return a[num]
}
